package Leetcode第一期;

public class 删除链表的节点_18 {
    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }
    public ListNode deleteNodeA(ListNode head, int val) {
        //思路：分情况讨论，删除相应的结点。
        if (head == null) {return null;}

        //删除头结点时
        if (head.val == val) {return head.next;}

        ListNode cur=head.next;
        ListNode pre=head;
        while (cur!=null){
            if (cur.val==val){
                //若当前节点是删除节点
                pre.next=cur.next;
                cur.next=null;
                cur=pre.next;
                break;
            }else {
                pre=cur;
                cur=cur.next;
            }
        }
        return  head;
    }



        public ListNode deleteNode(ListNode head, int val) {
            //思路：分情况讨论，删除相应的结点。
            if (head == null) {return null;}

            //删除头结点时
            if (head.val == val) return head.next;

            ListNode pre = head;
            ListNode cur = head.next;

            while (cur != null) {
                if (cur.val == val) {
                    pre.next = cur.next;
                    cur.next = null;
                    cur = pre.next;
                    break;
                }
                pre = cur;
                cur = cur.next;
            }
            return head;
        }

}
